package com.zr.bookcorner.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import com.zh.baselibrary.views.BadgeView;
import com.zr.bookcorner.R;

import java.util.List;

/**
 * @author EnzoChan
 * @create 2019/3/19
 * @desc:
 */
public class TabPageAdapter extends FragmentPagerAdapter {

    private Context mContext;
    private List<Fragment> fragments;
    private String[] tabNames;
    private List<Integer> mBadgeCountList;

    public TabPageAdapter(Context mContext, FragmentManager fm, List<Fragment> fragments, String[] tabNames, List<Integer> mBadgeCountList) {
        super(fm);
        this.mContext = mContext;
        this.fragments = fragments;
        this.tabNames = tabNames;
        this.mBadgeCountList = mBadgeCountList;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

    //重写getPageTitle方法
    @Override
    public CharSequence getPageTitle(int position) {
        //返回tab选项的名字
        return tabNames[position];
    }

    public View getTabItemView(int position) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.tab_layout_item, null);
        TextView textView =  view.findViewById(R.id.textview);
        textView.setText(tabNames[position]);

        View target = view.findViewById(R.id.badgeview_target);

        BadgeView badgeView = new BadgeView(mContext);
        badgeView.setTargetView(target);
//        badgeView.setBadgeMargin(0, 6, 10, 0);
//        badgeView.setTextSize(16);
        badgeView.setText(formatBadgeNumber(mBadgeCountList.get(position)));

        return view;
    }

    public static String formatBadgeNumber(int value) {
        if (value <= 0) {
            return null;
        }

        if (value < 100) {
            // equivalent to String#valueOf(int);
            return Integer.toString(value);
        }

        // my own policy
        return "99+";
    }
}

